//
//  NetworkOperation.m
//  IconMaster
//
//  Created by nhn on 14-9-16.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "NetworkOperation.h"
#import "NetworkAPI.h"
#import "DBUtil.h"
#import "JSONKit.h"

@implementation NetworkOperation

+ (void)getNewGroups:(void (^)(bool))block
{
    CATCH_EXCEPTION_BEGIN
    int maxid = 0;
	NSArray* resultArray = [DBUtil query:@"select max(globalid) as mid from grp"];
    if (resultArray.count) {
        maxid = (int)[[[resultArray objectAtIndex:0] objectForKey:@"mid"] integerValue];
    }
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [params setObject:[NSNumber numberWithInt:maxid] forKey:@"group_id"];
    
    [[NetworkAPI sharedInstance] command:@"get_new_group"
                           withParameter:params
                              onComplete:^(NSDictionary *json) {
                                  BOOL succeed = true;
                                  if ([json objectForKey:@"result"]) {
                                      succeed = true;
                                      
                                      for (NSDictionary* dict in [json objectForKey:@"result"]) {
                                          NSString* name = [dict objectForKey:@"name"];
                                          NSString* type = [dict objectForKey:@"type"];
                                          NSNumber* globalid = [dict objectForKey:@"id"];
                                          NSString* globalpath = [dict objectForKey:@"path"];
                                          NSString* globalfiles = [dict objectForKey:@"files"];
                                          
										  [DBUtil openDBWithBlock:^(FMDatabase *database) {
											  [database executeUpdateWithFormat:@"insert into grp(id, name, type, globalid, globalpath, downloaded) values(NULL, %@, %@, %@, %@, 1)", name, type, globalid, globalpath];
											  
											  int thegroupid = -1;
											  FMResultSet* rst = [database executeQueryWithFormat:@"select id from grp where globalid=%@", globalid];
											  if ([rst next]) {
												  thegroupid = [rst intForColumnIndex:0];
											  }
											  
											  if (thegroupid != -1) {
												  NSArray* filesDict = [globalfiles objectFromJSONString];
												  for (int i=0; i<filesDict.count; i++) {
    												  NSString* globalName = [filesDict objectAtIndex:i];
    												  [database executeUpdateWithFormat:@"insert into img(id, path, grpid, globalname) values(NULL, ':default_icon.png', %d, %@)", thegroupid, globalName];
												  }
											  }
										  }];
                                      }
                                  } else {
                                      succeed = false;
                                  }
                                  
                                  if (block) {
                                      block(succeed);
                                  }
								  
								  [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_GET_NEW_GROUP object:nil];
                              }];
    CATCH_EXCEPTION_END
}

+ (void)getNewConfig:(void (^)(bool))block
{
    CATCH_EXCEPTION_BEGIN
    NSString* configVersion = @"0";
	NSArray* resultArray = [DBUtil query:@"select * from cfg where key=%@", @"cfg_version"];
    if (resultArray.count) {
        configVersion = [[resultArray objectAtIndex:0] objectForKey:@"value"];
    }
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [params setObject:configVersion forKey:@"config_id"];
	
    [[NetworkAPI sharedInstance] command:@"get_new_config"
                           withParameter:params
                              onComplete:^(NSDictionary *json) {
                                  BOOL succeed = true;
                                  if ([json objectForKey:@"result"]) {
                                      succeed = true;
                                      
                                      [DBUtil openDBWithBlock:^(FMDatabase *database) {
                                          int maxid = configVersion.intValue;
                                          for (NSDictionary* dict in [json objectForKey:@"result"]) {
                                              NSString* key = [dict objectForKey:@"title"];
                                              NSString* value = [dict objectForKey:@"content"];
                                              NSNumber* version = [dict objectForKey:@"version"];
                                              
                                              if (version.integerValue > maxid) {
                                                  maxid = (int)version.integerValue;
                                              }
                                              
                                              [database executeUpdateWithFormat:@"insert or replace into cfg(key, value) values(%@, %@)", key, value];
                                          }
										  
										  if (maxid != configVersion.intValue) {
											  [database executeUpdateWithFormat:@"insert or replace into cfg(key, value) values(%@, %d)", @"cfg_version", maxid];
										  }
                                      }];
                                  } else {
                                      succeed = false;
                                  }
								  
//								  [DBUtil printQuery:@"select * from cfg"];
								  
                                  if (block) {
                                      block(succeed);
                                  }
                              }];
    CATCH_EXCEPTION_END
}

+ (void)updateDeviceToken:(NSString *)token finishBlock:(void (^)(bool))block
{
    CATCH_EXCEPTION_BEGIN
	NSString* tokenKey = @"device_token";
    NSString* oldToken = @"";
    NSString* isFree = @"1";
	NSArray* resultArray = [DBUtil query:@"select * from cfg where key=%@", tokenKey];
    if (resultArray.count) {
        oldToken = [[resultArray objectAtIndex:0] objectForKey:@"value"];
    }
	
	if ([oldToken isEqualToString:token]) {
		if (block) {
			block(YES);
		}
		NSLog(@"do not need to upload device token");
		return;
	}
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [params setObject:oldToken forKey:@"old_token"];
    [params setObject:token forKey:@"new_token"];
    [params setObject:PreferredLanguage() forKey:@"pre_lan"];
    [params setObject:isFree forKey:@"is_free"];
	
    [[NetworkAPI sharedInstance] command:@"update_device_token"
                           withParameter:params
                              onComplete:^(NSDictionary *json) {
                                  BOOL succeed = true;
								  BOOL needSave = false;
								  
                                  if ([json objectForKey:@"result"]) {
                                      succeed = true;
									  needSave = true;
                                  } else {
                                      succeed = false;
									  
									  if ([json objectForKey:@"error"]) {
										  if ([[json objectForKey:@"error"] rangeOfString:@"database" options:NSCaseInsensitiveSearch].location != NSNotFound) {
											  needSave = true;
										  }
									  }
                                  }
								  
								  if (needSave) {
									  [DBUtil update:@"insert or replace into cfg(key, value) values(%@, %@)", tokenKey, token];
								  }
                                  
                                  if (block) {
                                      block(succeed);
                                  }
                              }];
	CATCH_EXCEPTION_END
}

+ (void)getNewSql:(NetworkFinishBlock)block
{
    CATCH_EXCEPTION_BEGIN
	NSString* sqlVersionKey = @"sql_version";
    NSString* oldVersion = @"0";
	NSArray* resultArray = [DBUtil query:@"select * from cfg where key=%@", sqlVersionKey];
    if (resultArray.count) {
        oldVersion = [[resultArray objectAtIndex:0] objectForKey:@"value"];
    }
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [params setObject:oldVersion forKey:@"sql_id"];
	
    [[NetworkAPI sharedInstance] command:@"get_new_sql"
                           withParameter:params
                              onComplete:^(NSDictionary *json) {
                                  BOOL succeed = true;
                                  if ([json objectForKey:@"result"]) {
                                      succeed = true;
                                      
                                      [DBUtil openDBWithBlock:^(FMDatabase *database) {
                                          int maxid = 0;
                                          
                                          for (NSDictionary* dict in [json objectForKey:@"result"]) {
                                              NSNumber* version = [dict objectForKey:@"id"];
                                              NSString* sql = [dict objectForKey:@"content"];
                                              
                                              if (version.integerValue > maxid) {
                                                  maxid = (int)version.integerValue;
                                              }
                                              
                                              [database executeUpdate:sql];
                                              [database executeUpdateWithFormat:@"insert or replace into cfg(key, value) values(%@, %d)", sqlVersionKey, maxid];
                                          }
                                      }];
                                  } else {
                                      succeed = false;
                                  }
                                  
                                  if (block) {
                                      block(succeed);
                                  }
                              }];
    CATCH_EXCEPTION_END
}

+ (void)sendFeedBack:(NSDictionary*)dict finishBlock:(NetworkFinishBlock)block {
    if (!dict) {
        if (block) {
            block(NO);
        }
        return;
    }
    
    CATCH_EXCEPTION_BEGIN
    NSString* savedIdKey = @"feedback_id";
    [[NetworkAPI sharedInstance] command:@"send_feedback"
                           withParameter:dict
                              onComplete:^(NSDictionary *json) {
                                  BOOL succeed = true;
                                  if ([json objectForKey:@"result"]) {
                                      succeed = true;
                                      
                                      NSString* savedIdString = nil;
                                      for (NSDictionary* dict in [json objectForKey:@"result"]) {
                                          NSNumber* globalid = [dict objectForKey:@"id"];
                                          NSArray* savedIdArray = [DBUtil query:@"select key, value from cfg where key=%@", savedIdKey];
                                          if (savedIdArray && savedIdArray.count) {
                                              savedIdString = [[savedIdArray objectAtIndex:0] objectForKey:@"value"];
                                          }
                                          
                                          if (globalid && ![globalid isKindOfClass:[NSNull class]]) {
                                              if (savedIdString) {
                                                  savedIdString = [savedIdString stringByAppendingFormat:@",%@", globalid];
                                              } else {
                                                  savedIdString = [NSString stringWithFormat:@"%@", globalid];
                                              }
                                          }
                                          
                                          if (savedIdString) {
                                              [DBUtil update:@"insert or replace into cfg(key, value) values(%@, %@)", savedIdKey, savedIdString];
                                          }
                                      }
                                  } else {
                                      succeed = false;
                                  }
                                  
                                  if (block) {
                                      block(succeed);
                                  }
                              }];
    CATCH_EXCEPTION_END
}

@end
